package org.example;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.stream.Stream;

public class FileCleaner {
    /**
     * 删除指定目录中今天之前修改的文件
     *
     * @param directoryPath      要清理的目录路径
     * @param deleteEmptyFolders 是否删除空文件夹
     * @throws IOException
     */
    public static void deleteFilesModifiedBeforeToday(String directoryPath, boolean deleteEmptyFolders) throws IOException {
        File directory = new File(directoryPath);

        if (!directory.exists() || !directory.isDirectory()) {
            throw new IllegalArgumentException("提供的路径不是有效目录: " + directoryPath);
        }

        // 获取今天的日期（不含时间部分）
        LocalDate today = LocalDate.now();

        // 遍历目录中的文件
        try (Stream<Path> paths = Files.walk(directory.toPath())) {
            paths.filter(Files::isRegularFile) // 只处理普通文件
                    .sorted(Comparator.reverseOrder()) // 反向排序，先处理子目录中的文件
                    .forEach(path -> {
                        try {
                            BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
                            LocalDate lastModifiedDate = attrs.lastModifiedTime()
                                    .toInstant()
                                    .atZone(ZoneId.systemDefault())
                                    .toLocalDate();

                            // 如果文件修改日期在今天之前
                            if (lastModifiedDate.isBefore(today)) {
//                                System.out.println("删除文件: " + path + " (修改时间: " + lastModifiedDate + ")");
                                Files.delete(path);
                            }
                        } catch (IOException e) {
                            System.err.println("无法删除文件: " + path + " - " + e.getMessage());
                        }
                    });
        }

        // 如果需要删除空文件夹
        if (deleteEmptyFolders) {
            deleteEmptyDirectories(directory);
        }
    }

    /**
     * 递归删除空文件夹
     *
     * @param directory 要检查的目录
     */
    private static void deleteEmptyDirectories(File directory) {
        File[] subDirs = directory.listFiles(File::isDirectory);
        if (subDirs != null) {
            for (File subDir : subDirs) {
                deleteEmptyDirectories(subDir); // 递归处理子目录
            }

            // 删除空目录
            if (directory.list().length == 0) {
                try {
                    System.out.println("删除空文件夹: " + directory.getAbsolutePath());
                    Files.delete(directory.toPath());
                } catch (IOException e) {
                    System.err.println("无法删除文件夹: " + directory + " - " + e.getMessage());
                }
            }
        }
    }
}
